import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import { viteVConsole } from "vite-plugin-vconsole";
import pxtovw from "postcss-px-to-viewport";
import bundleAnalyzer from "rollup-plugin-bundle-analyzer";
import vueJsx from "@vitejs/plugin-vue-jsx";
import legacy from "@vitejs/plugin-legacy";

// https://vitejs.dev/config/


export default ({ mode }) => {
  // const env = loadEnv(mode, "./config/", "VITE_");
  // console.log(env);

  /** 根据打包命令判断是否需要开启打包分析 */
  let isStartAnalyze: boolean = false;
  try {
    isStartAnalyze =
      JSON.parse(process.env.npm_config_argv)?.original?.[0] === "analyze";
  } catch (error) { }
  return defineConfig({
    base: "./",
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
    },
    build: {
      target: "es2015",
    },
    envDir: "./config/",
    plugins: [
      vueJsx(),
      isStartAnalyze ? bundleAnalyzer({}) : undefined,
      vue(),
      mode === "prod"
        ? viteVConsole({
          entry: path.resolve("src/main.ts"), // 或者可以使用这个配置: [path.resolve('src/main.ts')]
          localEnabled: true,
          enabled: true,
          config: {
            maxLogNumber: 1000,
            theme: "light",
          },
        })
        : undefined,
      legacy({
        targets: [
          "Android > 39",
          "Chrome >= 60",
          "Safari >= 10.1",
          "iOS >= 10.3",
          "Firefox >= 54",
          "Edge >= 15",
        ],
      }),
    ],
    server: {
      https: false,
      host: "0.0.0.0",
      port: 9527,
      proxy: {
        "/wsc": {
          target: (() => {
            return mode !== "prod"
              ? "https://testb2ch5.gcongo.com.cn"
              : "https://gw.vgogbuy.com";
          })(),
          changeOrigin: true,
        },
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          math: "always",
        },
      },
      postcss: {
        plugins: [
          pxtovw({
            viewportWidth: 375,
            viewportUnit: "vw",
          })
        ],
      },
    },
  });
};
